import 'package:easy_read_comic/internal/api/book_api.dart';
import 'package:easy_read_comic/models/page_model.dart';
import 'package:get/get.dart';

import '../../models/comic_model.dart';

class BookController extends GetxController {
  List<ComicModel> list = [];

  int currentPage = 0;

  bool done = false;

  @override
  void onInit() {
    super.onInit();
    this.loadMore();
  }

  loadMore() {
    if (this.done) {
      return;
    }
    BookApi().getList(currentPage: currentPage).then(
      (response) {
        var data = response.data["data"]["List"] ?? [];
        for (var item in data) {
          this.list.add(ComicModel.formJson(item));
        }
        var page = PageModel.fromJson(response.data["data"]["Page"]);
        if (page.hasNextPage) {
          this.currentPage = page.NextPage;
        } else {
          this.done = true;
        }
        this.update();
      },
    ).catchError((err) {
      print(err);
    });
  }

  resetLoad() {
    this.done = false;
    this.currentPage = 0;
    this.list.clear();
    this.update();
    Future.delayed(Duration(seconds: 2), this.loadMore());
  }
}
